package com.governtalk.backend.service.impl;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.governtalk.backend.service.CozeFileRetrieveService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

@Service
public class CozeFileRetrieveServiceImpl implements CozeFileRetrieveService {

    @Value("${ai.coze.api-key:default-api-key}")
    private String apiKey;

    private final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public String retrieveFileContent(String fileId) {
        System.out.println("=== 开始检索文件内容 ===");
        System.out.println("文件ID: " + fileId);

        try {
            // Coze文件检索API端点
            URL url = new URL("https://api.coze.cn/open_api/v2/file/retrieve");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            // 设置请求方法
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Authorization", "Bearer " + apiKey);
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setDoOutput(true);

            // 构建请求体
            String requestBody = String.format("{\"file_id\": \"%s\"}", fileId);
            System.out.println("文件检索请求体: " + requestBody);

            // 发送请求
            try (java.io.OutputStream outputStream = connection.getOutputStream()) {
                byte[] input = requestBody.getBytes(StandardCharsets.UTF_8);
                outputStream.write(input, 0, input.length);
            }

            // 读取响应
            int responseCode = connection.getResponseCode();
            System.out.println("文件检索响应码: " + responseCode);

            String responseBody;
            if (responseCode == HttpURLConnection.HTTP_OK) {
                try (BufferedReader reader = new BufferedReader(
                        new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
                    StringBuilder response = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) {
                        response.append(line);
                    }
                    responseBody = response.toString();
                }
            } else {
                try (BufferedReader reader = new BufferedReader(
                        new InputStreamReader(connection.getErrorStream(), StandardCharsets.UTF_8))) {
                    StringBuilder response = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) {
                        response.append(line);
                    }
                    responseBody = response.toString();
                }
            }

            System.out.println("文件检索响应: " + responseBody);

            if (responseCode == HttpURLConnection.HTTP_OK) {
                JsonNode jsonResponse = objectMapper.readTree(responseBody);
                if (jsonResponse.has("data") && jsonResponse.get("data").has("content")) {
                    String content = jsonResponse.get("data").get("content").asText();
                    System.out.println("✅ 文件内容检索成功，内容长度: " + content.length());
                    return content;
                } else {
                    throw new RuntimeException("响应中未找到文件内容: " + responseBody);
                }
            } else {
                throw new RuntimeException("文件检索失败，响应码: " + responseCode + ", 响应: " + responseBody);
            }

        } catch (IOException e) {
            System.err.println("❌ 文件内容检索失败: " + e.getMessage());
            e.printStackTrace();
            throw new RuntimeException("文件内容检索失败: " + e.getMessage(), e);
        }
    }
}

